
import Vue from 'vue'
// 1.引入vuex
import Vuex from 'vuex'
import { checkLoginNameAndPassword } from '@/api/employee.js'

Vue.use(Vuex)


//用来全局定义一些共享的数据状态
const state = {
    name: 'syk',
    user: {
        name: '张三',
        age: 18
    },
    UserList: [
        //数组数据
        { name: '张三', age: 18 },
        { name: '李四', age: 19 },
    ],

    isLoggedIn: false //是否登录

}


//定义一些修改state中数据的函数
const mutations = {
    //修改state中的数据，第一个参数是state，第二个参数是传进来的数据
    updateName(state, name) {
        state.name = name
    },
    updateUser(state, user) {
        state.user = user
    },
    addUser(state, user) {
        state.UserList.push(user)
    },
    SET_LOGGED_IN(state, isLoggedIn) {
        state.isLoggedIn = isLoggedIn,
            localStorage.setItem('isLoggedIn', isLoggedIn); //存储到本地
    },
    SET_USER(state, user) {
        state.user = user,
            localStorage.setItem('user', JSON.stringify(user)); //存储到本地
    },

}

//响应组件中的事件 异步操作和提交mutation
const actions = {
    async login({ commit }, user) {
        let status = false;
        try {
            const res = await checkLoginNameAndPassword(user);
            console.log(res);
            if (res.code === 200) {
                commit('SET_LOGGED_IN', true);
                commit('SET_USER', user);
                status = true;
            }
        } catch (error) {
            console.error(error);
        }
        return status;
    }
}


//定义一些获取state中数据的函数
const getters = {
    getAllAges(state) {
        //获取总数据
        let allAges = 0
        state.UserList.forEach(user => {
            allAges += user.age
        })
        return allAges
    }
}



2.//创建store对象
const store = new Vuex.Store({
    state,
    mutations,
    actions,
    getters
})

3.//将store对象导出
export default store;
